<?php

namespace app\controller;

use app\general\ApiResponse;
use app\general\utils\ConversionUtils;
use app\model\Column;
use support\Db;
use support\Request;

class ColumnController
{
    use ApiResponse;
    public function index(Request $request)
    {

        $users = Db::table('columns')
        ->when(is_numeric($request->input('status')) , function ($query) use ($request) {
            return $query->where('status', $request->input('status'));
        })->when($request->input('type'), function ($query) use ($request) {
            return $query->where('type', $request->input('type'));
        })
        ->paginate(10);
        $items = $users->items();
        foreach ($items as $key=>$val){
            $items[$key] = ConversionUtils::underscoreToHump($val) ;
        }
        return  json($this->success('操作成功',$items,$users->total()));
    }

    /**
     * 创建
     * @param Request $request
     * @return \support\Response
     */
    public function store(Request $request)
    {
        $column = new Column();
        $column->setRawAttributes(ConversionUtils::humpToUnderscore($request->all()));
        $column->version=0;
        $column->save();
        return  json($this->success('操作成功'));
    }

    /**
     * 更新
     * @param Request $request
     * @param $id
     * @return \support\Response
     */
    public function update(Request $request,$id)
    {
        $Column = Column::find($id);
        if(empty($Column)){
            return  json($this->success('操作失败'));
        }
        $data = $request->all();
        $data = ConversionUtils::humpToUnderscore($data);
        unset($data['create_time'],$data['updateTime']);
        $Column->setRawAttributes($data);
        $Column->save();
        return  json($this->success('操作成功'));
    }

    public function destroy(Request $request, $id)
    {
        Column::destroy($id) ;
        return  json($this->success('操作成功'));
    }

    public function all(Request $request)
    {

        $items = Db::table('columns')
            ->when(is_numeric($request->input('status')) , function ($query) use ($request) {
                return $query->where('status', $request->input('status'));
            })->when($request->input('type'), function ($query) use ($request) {
                return $query->where('type', $request->input('type'));
            })->get();
            //->paginate(10);
        //$items = $users->items();
        foreach ($items as $key=>$val){
            $items[$key] = ConversionUtils::underscoreToHump($val) ;
        }
        return  json($this->successData('操作成功',$items));
    }

}
